package com.eveinfo.api.utils.skilllist;

import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.eveinfo.api.AbstractApiHandler;

public class SkillListHandler extends AbstractApiHandler<ApiSkills> {

	private ApiSkillGroup skillGroup;
	private ApiSkill skill;
	private LinkedList<String> where;

	public SkillListHandler() {
		super();
		response = new ApiSkills();
		where = new LinkedList<String>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			where.addFirst(attributes.getValue("name"));
		} else if (value.equals("row")) {
			String first = where.getFirst();
			if (first.equals("skillGroups")) {
				skillGroup = new ApiSkillGroup();
				skillGroup.setGroupName(attributes.getValue("groupName"));
				skillGroup.setGroupID(Integer.parseInt(attributes.getValue("groupID")));
			} else if (first.equals("skills")) {
				skill = new ApiSkill();
				skill.setGroupID(Integer.parseInt(attributes.getValue("groupID")));
				skill.setTypeID(Integer.parseInt(attributes.getValue("typeID")));
				skill.setTypeName(attributes.getValue("typeName"));
			} else if (first.equals("requiredSkills")) {
				ApiRequirement requirement = new ApiRequirement();
				requirement.setTypeID(Integer.parseInt(attributes.getValue("typeID")));
				requirement.setSkillLevel(Integer.parseInt(attributes.getValue("skillLevel")));
				skill.addRequiredSkill(requirement);
			} else if (first.equals("skillBonusCollection")) {
	
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		super.endElement(uri, localName, qName);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			where.removeFirst();
		} else if (value.equals("row")) {
			String first = where.getFirst();
			if (first.equals("skillGroups")) {
				response.addSkillGroup(skillGroup);
			} else if (first.equals("skills")) {
				skillGroup.addSkill(skill);
			}
		} else if (value.equals("description")) {
			if (where.getFirst().equals("skills")) {
				skill.setDescription(text);
			}
		} else if (value.equals("rank")) {
			if (where.getFirst().equals("skills")) {
				skill.setRank(Integer.parseInt(text));
			}
		} else if (value.equals("primaryAttribute")) {
			if (where.getFirst().equals("skills")) {
				skill.setPrimaryAttribute(text);
			}
		} else if (value.equals("secondaryAttribute")) {
			if (where.getFirst().equals("skills")) {
				skill.setSecondaryAttribute(text);
			}
		}
	}

}
